﻿CREATE PROCEDURE [Event].[CreateInvitation]
	@EventID INT,
	@BodyText NVARCHAR(MAX) = NULL,
	@InvitationSent SMALLDATETIME = NULL,
	@Attendees Event.AttendeeList READONLY,
	@InvitationID INT OUTPUT
WITH EXECUTE AS OWNER
AS
SET NOCOUNT ON;

DECLARE @AccountID AS INT;

BEGIN TRY
  BEGIN TRANSACTION
  
  INSERT INTO Event.[Invitations]
  (
    EventID,
    BodyText,
    InvitationSent
  )
  VALUES
  (
    @EventID,
    @BodyText,
    @InvitationSent
  );
  
  SET @InvitationID = SCOPE_IDENTITY();
  
  SELECT @AccountID = OwnerID
    FROM Event.Events
   WHERE EventID = @EventID;
  
  INSERT INTO Event.Attendees
  (
    EventID,
    AccountID,
    EmailAddress
  )
  SELECT @EventID,
         AccountID,
         EmailAddress
    FROM @Attendees;
  
  COMMIT TRANSACTION
END TRY
BEGIN CATCH
  SET @InvitationID = -1;

  IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION;
  
  DECLARE @ERROR_SEVERITY AS INT,
          @ERROR_STATE AS INT,
          @ERROR_NUMBER AS INT,
          @ERROR_LINE AS INT,
          @ERROR_MESSAGE AS NVARCHAR(4000);

  SELECT @ERROR_SEVERITY = ERROR_SEVERITY(),
         @ERROR_STATE = ERROR_STATE(),
         @ERROR_NUMBER = ERROR_NUMBER(),
         @ERROR_LINE = ERROR_LINE(),
         @ERROR_MESSAGE = ERROR_MESSAGE();

  RAISERROR('Msg %d, Line %d, :%s',
            @ERROR_SEVERITY,
            @ERROR_STATE,
            @ERROR_NUMBER,
            @ERROR_LINE,
            @ERROR_MESSAGE);
END CATCH